#include "waveformwidget.h"

WaveformWidget::WaveformWidget(QWidget *parent)
    : QWidget{parent}
{
    audioSamples.clear();
}

void WaveformWidget::setAudioSamples(const QVector<qint16> &samples, int toNum)
{
    audioSamples = samples;
    m_toNum = toNum;
    update();
}

void WaveformWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    if (audioSamples.isEmpty())
        return;

    painter.setPen(Qt::green);
    int numSamples = audioSamples.size();
    int maxSampleValue = qAbs(*std::max_element(audioSamples.constBegin(), audioSamples.constEnd()));
    qreal xScale = static_cast<qreal>(width() - 1) / (numSamples - 1);
    qreal yScale = static_cast<qreal>(height() - 1) / (2.1 * maxSampleValue);
    QPointF startPoint(0, height() / 2); // 从中间开始绘制
    for (int i = 1; i < numSamples; ++i)
    {
        QPointF endPoint(i * xScale, height() / 2 - audioSamples[i] * yScale); // 根据采样值计算终点位置
        painter.drawLine(startPoint, endPoint);                                // 绘制线条
        startPoint = endPoint;                                                 // 更新起点为当前终点，用于下一段线条的起点
    }

    // 在左上角绘制数字-显示最大值
    painter.setPen(Qt::white);                 // 设置画笔颜色为白色
    painter.setFont(QFont("Courier New", 12)); // 设置字体
    painter.drawText(QPoint(8, 18), "Len: " + QString::number(numSamples) + " " + QString::number(m_toNum));
    painter.drawText(QPoint(8, 36), "Max: " + QString::number(maxSampleValue));
}
